#!/bin/bash
# source ./a_function.sh ./
:<<!
一些公共方法
!

JQ_EXEC=`which jq`
#echo "=============引入文件 source ./a_function.sh============="

#CurrentDIR_Script_Absolute_Source_a_function命名为完整名字是为了避免其他source文件中也可能使用CurrentDIR_Script_Absolute从而导致数据混乱错误。
#CurrentDIR_Script_Absolute_Source_a_function="$( cd "$( dirname "$0" )" && pwd )"
CurrentDIR_Script_Absolute_Source_a_function=$1   #这个文件是soure进来的，所以最后把这个文件的所在目录传进来，不然会默认是当前目录./
if [ ${#CurrentDIR_Script_Absolute_Source_a_function} -eq 0 ]; then
    echo "000----------------$0"
    echo "111----------------$( realpath "$0" )"
    echo "222----------------$( cd "$( dirname "$0" )" && pwd )"
        CurrentDIR_Script=$PWD
    CurrentDIR_Script_Absolute_Source_a_function="${CurrentDIR_Script}"
    echo "温馨提示⚠️：您没设置 a_function.sh 的所在目录，将使用${CurrentDIR_Script_Absolute_Source_a_function}目录"
fi

if [ ! -f "${CurrentDIR_Script_Absolute_Source_a_function}/a_function.sh" ];then
    echo "❌:您a_function路径为${CurrentDIR_Script_Absolute_Source_a_function}/a_function.sh不正确，source引入本文件的脚本为$0，请检查！"
    exit 1
fi

bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute_Source_a_function}

qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_json_file_check_script_path="$(sh ${qscript_path_get_filepath} qbase json_file_check)"


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'



CommonScriptResultJSONFilePath="${bulidScriptCommon_dir_Absolute}/json/common_script_result.json"
function updatePackageErrorCodeAndMessage() {
    Update_code_message_SCRIPT_PATH="${bulidScriptCommon_dir_Absolute}/base/error_code_message/update_code_message.sh"
    if [ "$1" == 1 ]; then
        printf "${RED}$1:$2${NC}\n"
    else
        printf "${BLUE}$1:$2${NC}\n"
    fi
    sh "${Update_code_message_SCRIPT_PATH}" -codeMessageJsonF "${CommonScriptResultJSONFilePath}" -code "$1" -message "$2"
}

function getCurrentBranch() {
    FILE_PATH=$1

    currentBranchResult=$(git branch --show-current) # 获取当前分支
    currentBranchResultStringLength=${#currentBranchResult}
    if [ ${currentBranchResultStringLength} == 0 ]; then
        echo "$FUNCNAME 提示：此电脑环境未获取到本地分支(可能是jenkins问题),故将直接取直接传进来的分支"
        currentBranchResult=$(cat ${FILE_PATH} | ${JQ_EXEC} '.package_from_brance' | sed 's/\"//g')
    fi
    currentBranchResult=${currentBranchResult##*/} # 取最后的component
    echo "currentBranchResult=${currentBranchResult}"
}



exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}

function isContainInArray() {
    array=$1
    element=$2
    #echo "array=${array[@]}"
    #echo "element=${element}"
    if echo "${array[@]}" | grep -wq "${element}" &>/dev/null; then
        echo "Found ${element}"
        return 0
    else
        echo "NoFound ${element}"
        return 1
    fi
}

function updatePackageErrorCode() {
    FILE_PATH=$1
    New_PackageErrorCode=$2
    sh ${qbase_update_json_file_singleString_script_path} -jsonF ${FILE_PATH} -k 'package_code' -v "${New_PackageErrorCode}"
}

function updatePackageErrorMessage() {
    FILE_PATH=$1
    New_PackageErrorMessage=$2
    sh ${qbase_update_json_file_singleString_script_path} -jsonF ${FILE_PATH} -k 'package_message' -v "${New_PackageErrorMessage}"
}


#[在shell脚本中验证JSON文件的语法](https://qa.1r1g.com/sf/ask/2966952551/)
function check_jsonFile_valid() {
    sh ${qbase_json_file_check_script_path} -checkedJsonF "$1" -scriptResultJsonF "$2"
}

function check_jsonString_valid () {
    check_jsonFile_valid_log="==================执行方法:$FUNCNAME 检查$1文件"
    CheckJsonString=$1
    ShowResultTo_FILE_PATH=$2   # 检查结果的 code 和 message 保存到指定文件的 package_code 和 package_message 中
    #echo "CheckJsonString=${CheckJsonString}"
    
    JsonPPString=$(echo ${CheckJsonString} | json_pp)
    JsonPPLength=${#JsonPPString}
    #echo "JsonPPLength=${JsonPPLength}"
    if [ ${JsonPPLength} == 0 ]; then
        PackageErrorCode=-1
        PackageErrorMessage="${CheckJsonString}不是标准json格式的字符串，请检查"

        if [ -f "${ShowResultTo_FILE_PATH}" ]; then
            updatePackageErrorCode "${ShowResultTo_FILE_PATH}" ${PackageErrorCode}
            updatePackageErrorMessage "${ShowResultTo_FILE_PATH}" "${PackageErrorMessage}"
        fi
        echo "${check_jsonFile_valid_log}:失败❌"
        return 1
    fi

    #echo "${check_jsonFile_valid_log}:成功✅"
    return 0
}


function checkIfErrorExit() {
    FILE_PATH=$1
    PackageErrorCode=$(cat ${FILE_PATH} | ${JQ_EXEC} -r '.package_code') # -r 去除字符串引号
    if [ "${PackageErrorCode}" != "package_code_0" ] ; then
        sh noti_new_package.sh -appInfoF ${FILE_PATH} --log-robottype "error"
        exit_script
    fi
}


function getCommonScriptResultJSONResultCodeAndMessage() {
    CommonScriptResultJSON_PackageErrorCodeResult=$(cat ${CommonScriptResultJSONFilePath} | ${JQ_EXEC} -r '.package_code') # -r 去除字符串引号
    CommonScriptResultJSON_PackageErrorMessageResult=$(cat ${CommonScriptResultJSONFilePath} | ${JQ_EXEC} -r '.package_message') # -r 去除字符串引号
    if [ "${CommonScriptResultJSON_PackageErrorCodeResult}" != "package_code_0" ] ; then
        # printf "${RED}${CommonScriptResultJSONFilePath} 中package_code 的值不是 package_code_0 ，而是${CommonScriptResultJSON_PackageErrorCodeResult}，请检查${NC}\n"
        return 1
    else
        return 0
    fi
}


#!/bin/bash
 
function showArr(){
 
    arr=$1
 
    for i in ${arr[*]}; do
        echo "---------"
        echo $i
    done
 
}

# 接收两个参数，参数1:数组(必填)；参数2:是否转义(可空，默认false)
#参数1数组入参不同时候，有时候会有问题，暂时去掉转义功能
function getJsonStringFromArray() {
    #echo "\n以下为>>>>>>>>>>>>$0执行将数组转为json字符串的操作>>>>>>>>>>>>"
#    echo "入参:$1"

    local arrayArg
    arrayArg=(` echo "$@" `)
#    arrayArg=($1)
    
#    shouldEscape=$2
#    if [ -z "$2" ]; then
#        shouldEscape="false" # 是否要转义
#    fi
#    echo "是否要转义shouldEscape=${shouldEscape}"
    

    #echo "arrayArg=${arrayArg[*]}"
    arrayLength=${#arrayArg[*]}
    #echo "arrayLength=${arrayLength}"
    if [ ${arrayLength} == 0 ]; then
        return 1
    fi


    if [ ${arrayLength} == 1 ]; then
        devBranceMap=${arrayArg[0]}
        #echo "------------------0:${devBranceMap}"
        arrayJsonResultString="["
        arrayJsonResultString+=${devBranceMap}
        arrayJsonResultString+="]"
    else
        for ((i=0;i<${arrayLength};i++))
        do
            devBranceMap=${arrayArg[i]}
            #echo "------------------${i}:${devBranceMap}"
            if [ ${i} == 0 ]; then
                arrayJsonResultString="["
            fi
            
#            if [ "${shouldEscape}" == "true" ]; then
#                arrayJsonResultString+="\""
#            fi
            arrayJsonResultString+=${devBranceMap}
#            if [ "${shouldEscape}" == "true" ]; then
#                arrayJsonResultString+="\""
#            fi
            
            if [ ${i} -lt $((arrayLength-1)) ]; then
                arrayJsonResultString+=","
            fi
            
            if [ ${i} == $((arrayLength-1)) ]; then
                arrayJsonResultString+="]"
            fi
        done
    fi
    
    #echo "arrayJsonResultString=${arrayJsonResultString}"
    #echo "<<<<<<<<<<<<以上为$0执行将数组转为json字符串的操作<<<<<<<<<<<<\n"
    return 0
}

function changePackageNameByAppInfoEnvironment() {
    FILE_PATH=$1
    ipa_file_path=$2
    
    ipa_dir_name=$(dirname "$ipa_file_path")
    ipa_file_name_and_extension=$(basename "$ipa_file_path")
    ipa_file_extension=${ipa_file_name_and_extension##*.}
#    echo "包的ipa_dir_name为${ipa_dir_name}"
#    echo "包的ipa_file_name_and_extension为${ipa_file_name_and_extension}"
#    echo "包的ipa_file_extension为${ipa_file_extension}"
    VERSION=$(cat ${FILE_PATH} | ${JQ_EXEC} -r ".version")
    BUILD=$(cat ${FILE_PATH} | ${JQ_EXEC} -r ".buildNumber")
    
    BRANCH=$(cat $FILE_PATH | ${JQ_EXEC} .package_from_brance | sed 's/\"//g')
    PlatformType=$(cat $FILE_PATH | ${JQ_EXEC} .platform_type | sed 's/\"//g')
    PackageTargetType=$(cat $FILE_PATH | ${JQ_EXEC} .package_default_target | sed 's/\"//g')
    PackageNetworkType=$(cat $FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')
#    echo "BRANCH=$BRANCH,PlatformType=$PlatformType,PackageTargetType=$PackageTargetType,PackageTargetType=$PackageTargetType"

    ipa_file_name_new="${PlatformType}_${PackageNetworkType}_${PackageTargetType}_${BRANCH}_${VERSION}($BUILD).${ipa_file_extension}"
    # 检查字符串是否包含空格
    if [[ $ipa_file_name_new =~ [[:space:]] ]]; then
        # 字符串中包含空格，使用 tr 命令删除空格
        ipa_file_name_new=$(echo $ipa_file_name_new | tr -d ' ')
    fi
    ipa_file_path_new="${ipa_dir_name}/${ipa_file_name_new}"
    mv ${ipa_file_path} ${ipa_file_path_new}
    if [ $? != 0 ]; then
        printf "${RED}执行命令失败(重命名文件失败)：《 ${YELLOW}mv ${ipa_file_path} ${ipa_file_path_new} ${RED}》${NC}\n"
        retun 1
    fi

    printf "${GREEN}包的新文件名为 ${BLUE}${ipa_file_path_new} (PS:原文件名 ${BLUE}${FILE_PATH} ${GREEN}。${NC}\n"
}


# 复制文件和目录(先将要额外拷贝的数据拷贝到 $copy_from_dir_path 中，以备后面一起拷贝出来)，避免后续打包其会被覆盖掉
function copyAllFileToFrom_andBackUpTo() {
  # 解析命令行选项和参数
  while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
      -copyDirFrom)
        copy_from_dir_path="$2"
        shift
        shift
        ;;
      -addAppInfoF)
        FILE_PATH="$2"
        shift
        shift
        ;;
      -addExtraPaths)
        extra_paths=("$2")
        shift
        shift
        ;;
      -copyDirTo)
        copy_to_dir_path="$2"
        shift
        shift
        ;;
      *) # 未知选项
        echo "Unknown option: $1"
        return 1
        ;;
    esac
  done

  # 检查必需的参数是否已设置
  if [[ -z "$copy_from_dir_path" || -z "$FILE_PATH" || -z "$copy_to_dir_path" ]]; then
    echo "Missing required parameter."
    return 1
  fi

  # 创建输出目录
  mkdir -p "$copy_to_dir_path"

  # 复制文件和目录(先将要额外拷贝的数据拷贝到 $copy_from_dir_path 中，以备后面一起拷贝出来)
  echo "正在拷贝 $FILE_PATH 到 $copy_from_dir_path"
  cp "$FILE_PATH" "$copy_from_dir_path"

    echo "=====所有待添加的路径====== addExtraPaths =${extra_paths[*]}"
  for extra_path in "${extra_paths[@]}"; do
    echo "拷贝 $extra_path 到 $copy_from_dir_path"
    cp -r "$extra_path" "$copy_from_dir_path"
  done

  echo "Copy completed successfully."

    
    
    origin_copy_ipa_dir_name=${copy_from_dir_path##*/} # 取最后的component
#    echo "旧origin_copy_ipa_dir_name=${origin_copy_ipa_dir_name}"
    
    
    
    VERSION=$(cat $FILE_PATH | ${JQ_EXEC} .version | sed 's/\"//g')
    BUILD=$(cat $FILE_PATH | ${JQ_EXEC} .buildNumber | sed 's/\"//g')
    BRANCH=$(cat $FILE_PATH | ${JQ_EXEC} .package_from_brance | sed 's/\"//g')
    PlatformType=$(cat $FILE_PATH | ${JQ_EXEC} .platform_type | sed 's/\"//g')
    PackageTargetType=$(cat $FILE_PATH | ${JQ_EXEC} .package_default_target | sed 's/\"//g')
    PackageNetworkType=$(cat $FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')
    #echo "BRANCH=$BRANCH,PlatformType=$PlatformType,PackageTargetType=$PackageTargetType,PackageTargetType=$PackageTargetType"
    new_copy_ipa_dir_name="${origin_copy_ipa_dir_name}_${BRANCH}_${PlatformType}${VERSION}($BUILD)"
#    echo "新new_copy_ipa_dir_name=${new_copy_ipa_dir_name}"

    target_ipa_dir_path="${copy_to_dir_path}/${PackageNetworkType}/${PackageTargetType}"
#    echo "要转移输出到的目录:${target_ipa_dir_path}"
    
    mkdir -p "${target_ipa_dir_path}"
    cp -r ${copy_from_dir_path} "${target_ipa_dir_path}" # -r 复制该目录下的所有子目录和文件
    mv "${target_ipa_dir_path}/${origin_copy_ipa_dir_name}" "${target_ipa_dir_path}/${new_copy_ipa_dir_name}"
    
    # 更新
    sh ${qbase_update_json_file_singleString_script_path} -jsonF ${FILE_PATH} -k 'package_url_result.package_local_backup_dir' -v "${target_ipa_dir_path}/${new_copy_ipa_dir_name}"
}
